//直接在里面，默认页面一打开就会执行
//获取标签
let ipt_account = document.getElementById("ipt_account");
let ipt_pwd = document.getElementById("ipt_pwd");
let cb_rem = document.getElementById("cb_rem");

//页面一打开就从localStorage中去寻找登录有关的数组
let users = JSON.parse(localStorage.getItem("users"));// [];
console.log(users);

//记住密码第二步
let rem_user = localStorage.getItem("rem_user");
// rem_user = rem_user ? JSON.parse(rem_user) : null;
if(rem_user){
	rem_user = JSON.parse(rem_user);
	ipt_account.value = rem_user.account;
	ipt_pwd.value = rem_user.pwd;
	cb_rem.checked = true;
}

/**
 * 登录方法
 */
function login(){
	//获取输入框的内容
	let account = ipt_account.value;
	let pwd = ipt_pwd.value;
	let rem = cb_rem.checked;
	console.log(account, pwd, rem);
	//数据校验
	//账号不能为空
	if(account.trim().length === 0){
		alert("请输入账号");
		return;
	}
	
	//密码不能为空
	if(pwd.trim().length < 6){
		alert("密码至少6位");
		return;
	}
	
	//较验通过
	let result = false;
	//判断登录结果
	for(let index in users) {
		let item = users[index];
		if(item === null) {
			continue;
		}
		if(item.account === account && item.pwd === pwd) {
			result = true;
			break;
		}
	}
	
	if(result){
		//登录成功
		//是否需要记住密码
		/**
		 * 记住密码
			 * 1、保存到localStorage中
			 * 2、页面一加载的时候就去localStorage中读取，如果有显示在对应的输入框中
		*/
	
	if(rem) {
			let rem_user = {
				account: account,
				pwd: pwd
			}
			//localStorage.setItem(key, value);key可以随意，但必须是字符串
			localStorage.setItem("rem_user", JSON.stringify(rem_user));
		}else {
			localStorage.setItem("rem_user", null);
		}
		
		//将用户账号存到sessionStorage中
		sessionStorage.setItem("account", account);
		//页面跳转
		location.href = "index.html";
	}else {
		//登录失败
		alert("账号或密码错误");
	}
}
function toReg(){
		location.href = "注册.html";
	}